In this article, I’m explaining the simple example of node.js that count the number of visits on the server.
In this article, I’m explaining an example to count the number of the visit on the server. Let’s create an example by the following code:
First of all, choose the location where you create the program. Here, I select the location C:\node and create a file that is counter.js.
var http = require('http');
var userCount = 0;
http.createServer(function (request, response) {
console.log('New connection');
userCount++;
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello!\n');
response.write('We have had '+userCount+' visits!\n');
response.end();
}).listen(3000);
console.log('Server started run at the http://localhost:8000');
At this example, we create a server at the port of 3000 and every time count the server created by the usercount variable.
When you run the program the first time a message generates Server started to run at the http://localhost:8000. Let’s run it by the command prompt.
We have to need to run on the browser at the http//:localhost:3000/. Let’s show that it into the browser:
We see that when the program first time run then give the Message We have had 1 visit! And also need to check at the console:
Here a new message to New Connection that we tell that new connection created.
In the browser when you refresh the page every time give the message and count the number visits.
We need to check that here, I refresh the page 4 times then the number of visits is 5 times. Let’s check:
Here give the message we have had 5 visits! And we turn to the console and look
that what happens in the console:
Here four New Connection messages generate that every time create the server method call.
I hope that this article is helpful for understanding server refresh mechanisms for
you. Thanks!
Anonymous User
06-Feb-2019Thank You for the help.